import 'dart:async';
import 'dart:ffi';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import '../../manager/ywx_manager.dart';
import '../bean/worksdo/equipment_management_bean.dart';
import '../bean/worksdo/equipment_management_bean.dart';
import '../bean/worksdo/hardware_collar_bean.dart';
import '../bean/worksdo/material_requisition_bean.dart';
import '../bean/wroks/dispatchingaudit_bean.dart';

///设备管理：我的工单：工单领用：五金领用
class HardwareCollarModel {
  ///获取五金类型
  static Future<AppHttpResult<HardwareTypeBean, String>> GetPickMaterType(
    BuildContext context,
    bool isEnableLoad, {
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer =
        new Completer<AppHttpResult<HardwareTypeBean, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetPickMaterType"; //获取五金类型
    queryParameters['data'] = AppDataConfig.getFactory()?.FactoryId; //工厂id
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('五金类型数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<HardwareTypeBean, String>>(AppHttpResult()
            ..Data = HardwareTypeBean()
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<HardwareTypeBean, String>>;
  }

  ///获取五金名称
  static Future<AppHttpResult<HardwareTypeBean, String>> GetMaterialForPicking(
    BuildContext context,
    String? MaterType,
    bool isEnableLoad, {
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer =
        new Completer<AppHttpResult<HardwareTypeBean, String>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetMaterialForPicking"; //获取五金名称
    var FactoryId = AppDataConfig.getFactory()?.FactoryId; //工厂id
    var _MaterType = MaterType ?? ""; //五金类型
    var data = "{FactoryId:$FactoryId,MaterType:'${_MaterType}'}";
    // print("提交参数：$data");
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('五金名称数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<HardwareTypeBean, String>>(AppHttpResult()
            ..Data = HardwareTypeBean()
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<HardwareTypeBean, String>>;
  }

  ///获取五金列表
  ///Matertype 五金类型
  ///MaterCode 五金名称编码
  static Future<AppHttpResult<List<HardwareBean>, HardwareBean>>
      GetListForPicking(
    BuildContext context,
    String Matertype,
    String MaterCode,
    bool isEnableLoad, {
    ResponseCallbackWithStringCode_? onError = null,
  }) async {
    Completer completer =
        new Completer<AppHttpResult<List<HardwareBean>, HardwareBean>>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "GetListForPicking"; //获取五金列表
    var FactoryId = AppDataConfig.getFactory()?.FactoryId; //工厂id
    var data =
        "{Matertype:'$Matertype', MaterCode:'$MaterCode', PageIndex:1, PageSize:10000, FactoryId:$FactoryId}";
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        // PrintUtils.printlnLong('五金列表数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        if (onError != null) {
          onError?.call(code, error);
        } else {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..postASync<AppHttpResult<List<HardwareBean>, HardwareBean>>(
              AppHttpResult()
                ..Data = <HardwareBean>[]
                ..t2 = HardwareBean())
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<HardwareBean>, HardwareBean>>;
  }

  ///提交
  ///五金领用
  ///IsConfirm 是否确认二次提交；二次确认提交，code 为 101
  static Future<AppHttpResult<String, String>?> AddMaterialPickBack(
      BuildContext context,
      EquipmentResponseData? data,
      bool IsConfirm,
      bool isEnableLoad) async {
    Completer completer = new Completer<AppHttpResult<String, String>?>();
    var url = Url.baseurl() + Url.repairOrder; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    var queryParameters = Map<String, dynamic>();
    queryParameters['type'] = "AddMaterialPickBack"; //五金领用
    // queryParameters['data'] = data?.equipmentInfo?.Id; //工单id
    var submitHardwareReceive = data?.submitHardwareReceive;
    var FactoryId = AppDataConfig.getFactory()?.FactoryId; //工厂id
    submitHardwareReceive?.RepairOrderId = data?.equipmentInfo?.Id; //工单id
    submitHardwareReceive?.FactoryId = FactoryId;
    submitHardwareReceive?.IsConfirm = IsConfirm;
    var json = submitHardwareReceive?.jsonEncodeToJson();
    queryParameters['data'] = json;
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // PrintUtils.printlnLong('搜索数据：${ searchInfo?.jsonEncodeToJson()}');
    // InsertStartDatetime":"2024-04-16","InsertEndDatetime":"2024-04-16"
    // PrintUtils.printlnLong('五金领用提交数据：${json}');
    // print("${json}");
    // return Future.value(null);
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    // print("$url");
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"Res":true,"MsgCode":"100","MsgDetail":"","Data":"","TotalRowCount":0}
        // print('五金领用提交数据返回:\n$result');
        // {"Res":false,"MsgCode":"0","MsgDetail":"您已接过单","Data":null,"TotalRowCount":0}
        // PrintUtils.printlnLong('五金领用数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>?>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        // print("==================================到这里了");
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>?>;
  }
}
